package com.qq.weixin.service;

import java.io.IOException;
import java.text.MessageFormat;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.qq.weixin.model.ResultInfo;
import com.qq.weixin.model.basic.AccessToken;
import com.qq.weixin.model.msg.BaseCusMsg;
import com.qq.weixin.util.Constants;

public class BasicService {
	Logger logger = Logger.getLogger(BasicService.class);
	private CloseableHttpClient httpclient = HttpClients.createDefault();
	private JsonParser parser = new JsonParser();

	public AccessToken getAccessToken(String appid, String secret) {
		HttpGet getReq = new HttpGet(
				MessageFormat
						.format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}",
								"client_credential", appid, secret));

		AccessToken accessToken = new AccessToken();
		CloseableHttpResponse getResp = null;
		try {
			getResp = httpclient.execute(getReq);
			String jsonstr = EntityUtils.toString(getResp.getEntity(), "utf-8");
			JsonElement element = parser.parse(jsonstr);
			ResultInfo resultInfo = ResultInfo.convert(element);
			accessToken.setResultInfo(resultInfo);
			if (resultInfo.isSuccess()) {
				accessToken.setAccess_token(element.getAsJsonObject()
						.get("access_token").getAsString());
				accessToken.setExpires_in(element.getAsJsonObject()
						.get("expires_in").getAsLong());
			}
		} catch (Exception e) {
			logger.error("", e);
		} finally {
			if (getResp != null) {
				try {
					getResp.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}

		return accessToken;
	}

	/**
	 * 发送客服消息
	 * 
	 * @return
	 */
	public ResultInfo sendKfMessage(String accessToken, BaseCusMsg baseCusMsg) {
		HttpPost postReq = new HttpPost(
				MessageFormat
						.format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}",
								accessToken));

		HttpEntity entity = new StringEntity(JSON.toJSONString(baseCusMsg),
				ContentType.APPLICATION_JSON);
		postReq.setEntity(entity);
		// System.out.println(postReq);
		CloseableHttpResponse getResp = null;
		ResultInfo resultInfo = null;
		try {
			getResp = httpclient.execute(postReq);
			String jsonstr = EntityUtils.toString(getResp.getEntity(),
					Constants.UTF_8);
			resultInfo = ResultInfo.convert(jsonstr);
		} catch (Exception e) {
			logger.error(e);
		} finally {
			if (getResp != null) {
				try {
					getResp.close();
				} catch (IOException e) {
					logger.error("", e);
				}
			}
		}
		return resultInfo;
	}

	public static void main(String[] args) {
		BasicService service = new BasicService();
		AccessToken token = service.getAccessToken("wxf1af8f31d007525f",
				"7607b9805c63ad5081ca5e01347ea9c7");
		System.out.println(token.getAccess_token() + ","
				+ token.getExpires_in() + "," + token.getResultInfo());
	}

}